<template>
  <div class="content-area">
    <!-- 类型切换标签 -->
    <div class="type-tabs-card">
      <div class="type-tabs">
        <el-radio-group
          v-model="activeStaffType"
          @change="handleTypeChangeHandle"
        >
          <el-radio-button value="all">全部行政人员</el-radio-button>
          <el-radio-button value="administrative_manager"
            >行政管理人员</el-radio-button
          >
          <el-radio-button value="administrative_technician"
            >行政技术人员</el-radio-button
          >
        </el-radio-group>
      </div>
    </div>

    <!-- 筛选卡片 -->
    <div class="filter-card">
      <div class="filter-row">
        <div class="filter-item">
          <div class="filter-label">人员姓名</div>
          <el-input
            v-model="filters.administrative_name"
            placeholder="请输入人员姓名"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">人员工号</div>
          <el-input
            v-model="filters.work_id"
            placeholder="请输入人员工号"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">所属部门</div>
          <el-select
            v-model="filters.department_id"
            placeholder="请选择部门"
            clearable
          >
            <el-option
              v-for="dept in administrativeDepartmentOptions"
              :key="dept.value"
              :label="dept.label"
              :value="dept.value"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">职称</div>
          <el-select
            v-model="filters.professional_id"
            placeholder="请选择职称"
            clearable
          >
            <el-option
              v-for="prof in filteredProfessionalOptions"
              :key="prof.value"
              :label="prof.label"
              :value="prof.value"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">状态</div>
          <el-select
            v-model="filters.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="在职" :value="1" />
            <el-option label="休假" :value="2" />
            <el-option label="离职" :value="3" />
          </el-select>
        </div>
      </div>
      <div class="action-buttons">
        <el-button @click="resetFiltersHandle">重置</el-button>
        <el-button type="primary" @click="searchAdministrativeStaffHandle"
          >查询</el-button
        >
        <el-button
          type="success"
          @click="showAddAdministrativeStaffDialogHandle"
        >
          <el-icon><Plus /></el-icon>
          新增行政人员
        </el-button>
      </div>
    </div>

    <!-- 行政人员表格 -->
    <div class="administrative-table">
      <div class="table-header">
        <div class="table-title">{{ getTableTitle() }}</div>
        <div class="table-tools">
          <el-button type="primary" @click="exportDataHandle">
            <el-icon><Document /></el-icon>
            导出数据
          </el-button>
          <el-button @click="refreshDataHandle">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <el-table
        :data="administrativeStaffList"
        style="width: 100%"
        stripe
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="work_id" label="工号" width="100" />
        <el-table-column label="人员信息" min-width="200">
          <template #default="{ row }">
            <div class="staff-info">
              <div class="staff-avatar">
                <el-avatar
                  :size="40"
                  :src="row.manager_avatar || defaultAvatar"
                />
              </div>
              <div>
                <div class="staff-name">{{ row.manager_name }}</div>
                <div class="staff-details">
                  <el-tag :type="getStaffTypeTag(row.staff_type)" size="small">
                    {{ formatStaffType(row.staff_type) }}
                  </el-tag>
                  ·
                  {{ row.department_name }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" width="80">
          <template #default="{ row }">
            {{ formatSex(row.sex) }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column label="职称" width="120">
          <template #default="{ row }">
            {{ formatTitle(row.professional_id) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="good_at"
          label="擅长领域"
          width="180"
          show-overflow-tooltip
        />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="
                row.status === 1
                  ? 'success'
                  : row.status === 2
                  ? 'warning'
                  : 'info'
              "
              size="small"
            >
              {{ formatStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons-cell">
              <el-button
                size="small"
                @click="viewAdministrativeStaffDetailsHandle(row)"
                >详情</el-button
              >
              <el-button
                size="small"
                type="primary"
                @click="editAdministrativeStaffHandle(row)"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteAdministrativeStaffHandle(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          :page-count="pagination.pageTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChangeHandle"
          @current-change="handleCurrentChangeHandle"
        />
      </div>
    </div>

    <!-- 新增/编辑行政人员对话框 -->
    <el-dialog
      v-model="administrativeDialog.visible"
      :title="administrativeDialog.isEdit ? '编辑行政人员信息' : '新增行政人员'"
      width="800px"
      :destroy-on-close="false"
    >
      <el-form
        :model="administrativeForm"
        label-width="100px"
        :rules="administrativeRules"
        ref="administrativeFormRef"
      >
        <div style="display: flex; gap: 20px">
          <div style="flex: 1">
            <!-- 人员照片上传 -->
            <el-form-item label="人员照片" prop="manager_avatar">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="beforeAvatarUploadHandle"
                :http-request="handleAvatarChangeHandle"
              >
                <el-avatar
                  :size="60"
                  :src="administrativeForm.manager_avatar || defaultAvatar"
                  style="cursor: pointer"
                />
                <div style="font-size: 12px; color: #909399; margin-top: 4px">
                  点击更换
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item label="人员类型" prop="staff_type">
              <el-select
                v-model="administrativeForm.staff_type"
                placeholder="请选择人员类型"
                @change="handleStaffTypeChangeHandle"
                :disabled="administrativeDialog.isEdit"
              >
                <el-option
                  label="行政管理人员"
                  value="administrative_manager"
                />
                <el-option
                  label="行政技术人员"
                  value="administrative_technician"
                />
                <el-option label="系统管理员" value="system_administrator" />
              </el-select>
            </el-form-item>
            <el-form-item label="人员工号" prop="work_id">
              <el-input
                v-model="administrativeForm.work_id"
                placeholder="请输入人员工号"
                :disabled="administrativeDialog.isEdit"
              />
            </el-form-item>
            <el-form-item label="人员姓名" prop="manager_name">
              <el-input
                v-model="administrativeForm.manager_name"
                placeholder="请输入人员姓名"
              />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="administrativeForm.sex">
                <el-radio :value="0">男</el-radio>
                <el-radio :value="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input
                v-model="administrativeForm.phone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </div>
          <div style="flex: 1">
            <el-form-item label="所属部门" prop="department_id">
              <el-select
                v-model="administrativeForm.department_id"
                placeholder="请选择部门"
              >
                <el-option
                  v-for="dept in administrativeDepartmentOptions"
                  :key="dept.value"
                  :label="dept.label"
                  :value="dept.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="职称" prop="professional_id">
              <el-select
                v-model="administrativeForm.professional_id"
                placeholder="请选择职称"
              >
                <el-option
                  v-for="prof in filterProfessionTitleOptions"
                  :key="prof.value"
                  :label="prof.label"
                  :value="prof.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select
                v-model="administrativeForm.status"
                placeholder="请选择状态"
              >
                <el-option label="在职" :value="1" />
                <el-option label="休假" :value="2" />
                <el-option label="离职" :value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="账户" prop="username">
              <template v-if="administrativeDialog.isEdit">
                <div style="line-height: 36px">
                  {{ administrativeForm.username }}
                </div>
              </template>
              <template v-else>
                <el-input
                  v-model="administrativeForm.username"
                  placeholder="请输入账户"
                />
              </template>
            </el-form-item>
            <el-form-item
              label="密码"
              prop="userpass"
              v-if="!administrativeDialog.isEdit"
            >
              <el-input
                v-model="administrativeForm.userpass"
                placeholder="请输入密码"
                type="password"
              />
            </el-form-item>
          </div>
        </div>
        <el-form-item label="擅长领域" prop="good_at">
          <el-input
            v-model="administrativeForm.good_at"
            placeholder="请输入擅长领域"
          />
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input
            v-model="administrativeForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入人员简介"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="administrativeDialog.visible = false"
          >取消</el-button
        >
        <el-button type="primary" @click="submitAdministrativeFormHandle"
          >确认</el-button
        >
      </template>
    </el-dialog>

    <!-- 右侧抽屉：行政人员详情 -->
    <el-drawer
      v-model="detailDrawer.visible"
      direction="rtl"
      size="600px"
      with-header
      :destroy-on-close="false"
    >
      <template #header>
        <div class="drawer-custom-header">
          <h3>行政人员详情</h3>
        </div>
      </template>

      <div class="drawer-content-wrapper">
        <!-- 顶部个人信息卡片 -->
        <div class="staff-profile-card">
          <div class="profile-header">
            <el-avatar
              :size="80"
              :src="detailInfo.manager_avatar || defaultAvatar"
              class="profile-avatar"
            />
            <div class="profile-info">
              <h2 class="staff-name">{{ detailInfo.manager_name }}</h2>
              <div class="staff-meta">
                <el-tag
                  :type="getStaffTypeTag(detailInfo.staff_type)"
                  size="small"
                >
                  {{ formatStaffType(detailInfo.staff_type) }}
                </el-tag>
                <span class="work-id">{{ detailInfo.work_id }}</span>
              </div>
              <div class="staff-status">
                <el-tag :type="statusTagType(detailInfo.status)" size="small">
                  {{ formatStatus(detailInfo.status) }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>

        <!-- 详细信息区域 -->
        <div class="detail-sections">
          <!-- 基本信息 -->
          <div class="detail-section">
            <div class="section-header">
              <el-icon><User /></el-icon>
              <span>基本信息</span>
            </div>
            <div class="section-content">
              <div class="info-grid">
                <div class="info-item">
                  <label>性别</label>
                  <span>{{ formatSex(detailInfo.sex) }}</span>
                </div>
                <div class="info-item">
                  <label>联系电话</label>
                  <span>{{ detailInfo.phone || "未填写" }}</span>
                </div>
                <div class="info-item">
                  <label>所属部门</label>
                  <span>{{
                    detailInfo.department_name ||
                    getDepartmentLabel(detailInfo.department_id)
                  }}</span>
                </div>
                <div class="info-item">
                  <label>职称</label>
                  <span>{{ formatTitle(detailInfo.professional_id) }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 账户信息 -->
          <div class="detail-section">
            <div class="section-header">
              <el-icon><Key /></el-icon>
              <span>账户信息</span>
            </div>
            <div class="section-content">
              <div class="info-grid">
                <div class="info-item">
                  <label>登录账户</label>
                  <span class="username">{{
                    detailInfo.username || "未设置"
                  }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 专业信息 -->
          <div class="detail-section">
            <div class="section-header">
              <el-icon><Briefcase /></el-icon>
              <span>专业信息</span>
            </div>
            <div class="section-content">
              <div class="info-item-full">
                <label>擅长领域</label>
                <div class="info-content">
                  {{ detailInfo.good_at || "未填写" }}
                </div>
              </div>
              <div class="info-item-full">
                <label>人员简介</label>
                <div class="info-content description-text">
                  {{ detailInfo.description || "暂无简介" }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="drawer-footer">
          <el-button @click="detailDrawer.visible = false">关闭</el-button>
          <el-button type="primary" @click="openEditFromDrawerHandle">
            <el-icon><Edit /></el-icon>
            编辑信息
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "vuex";
import {
  uploadAvatar,
  addManager,
  editManager,
  getDepartmentList,
  getAdminStaffProfessionalList,
  getAdminStaffPagerDataBySearch,
} from "@/api/api";

const store = useStore();

// 激活的人员类型
const activeStaffType = ref("all");

const filters = reactive({
  administrative_name: "",
  work_id: "",
  department_id: "",
  professional_id: "",
  status: "",
  management_level: "",
  technical_field: "",
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  pageTotal: 0,
  total: 0,
});

// 科室选项
const administrativeDepartmentOptions = ref([]);
// 所有职称选项
const professionalOptions = ref([]);
// 过滤后的职称信息选项用于添加和编辑
const filterProfessionTitleOptions = ref([]);

// 行政人员数据
const administrativeStaffList = ref([]);
const loading = ref(false);

// 对话框相关
const administrativeDialog = reactive({
  visible: false,
  isEdit: false,
});

// 详情抽屉
const detailDrawer = reactive({
  visible: false,
});

const detailInfo = reactive({
  administrative_id: null,
  work_id: "",
  manager_name: "",
  manager_avatar: "",
  staff_type: "",
  professional_id: null,
  sex: null,
  phone: "",
  status: null,
  department_id: null,
  department_name: "",
  good_at: "",
  description: "",
  username: "",
});

// 默认头像读取assets目录下的图片
const defaultAvatar = require("@/assets/img/default-avatar.jpeg");

const administrativeForm = reactive({
  manager_id: null,
  work_id: "",
  manager_name: "",
  manager_avatar: "",
  staff_type: "administrative_manager",
  professional_id: null,
  sex: 1,
  phone: "",
  status: 1,
  department_id: "",
  good_at: "",
  description: "",
  username: "",
  userpass: "",
});

// 表单验证规则
const administrativeRules = ref({
  work_id: [{ required: true, message: "请输入人员工号", trigger: "blur" }],
  manager_name: [
    { required: true, message: "请输入人员姓名", trigger: "blur" },
  ],
  staff_type: [
    { required: true, message: "请选择人员类型", trigger: "change" },
  ],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  department_id: [{ required: true, message: "请选择部门", trigger: "change" }],
  professional_id: [
    { required: true, message: "请选择职称", trigger: "change" },
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  username: [{ required: true, message: "请输入账户", trigger: "blur" }],
  userpass: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const administrativeFormRef = ref(null);

// 计算属性：筛选后的职称选项
const filteredProfessionalOptions = computed(() => {
  if (activeStaffType.value === "all") {
    return professionalOptions.value;
  }
  return professionalOptions.value.filter(
    (prof) => prof.staff_type === activeStaffType.value
  );
});

// 计算属性：对话框中的职称选项
const dialogProfessionalOptions = computed(() => {
  return professionalOptions.value.filter(
    (prof) => prof.staff_type === administrativeForm.staff_type
  );
});

// 监听类型切换
watch(activeStaffType, (newVal) => {
  handleTypeChangeHandle(newVal);
});

// 行政人员类型方法定义
const handleTypeChangeHandle = (val) => {
  pagination.currentPage = 1;
  //设置人员类型作为筛选对象
  loadAdministrativeStaff();
};

const resetFiltersHandle = () => {
  Object.keys(filters).forEach((key) => {
    filters[key] = "";
  });
  loadAdministrativeStaff();
};

const searchAdministrativeStaffHandle = () => {
  pagination.currentPage = 1;
  loadAdministrativeStaff();
};

// ================
// 加载行政部门信息
// 已检查正常
// ================
const loadAdministrativeDepartments = async () => {
  try {
    const res = await getDepartmentList();
    // 统一处理API响应
    let data = res;
    if (res && res.code == 200) {
      data = res.data;
    }

    if (data && data.code === 200 && Array.isArray(data.data)) {
      administrativeDepartmentOptions.value = data.data
        .filter((dept) => dept.department_type === 3) //科室类型3是行政科室
        .map((d) => ({
          value: Number(d.department_id),
          label: d.department_name,
        }));
    } else if (Array.isArray(data)) {
      administrativeDepartmentOptions.value = data
        .filter((dept) => dept.department_type === 3) //科室类型3是行政科室
        .map((d) => ({
          value: Number(d.department_id),
          label: d.department_name,
        }));
    } else {
      console.warn("getDepartmentList 返回格式异常：", data);
      ElMessage.warning("加载部门数据格式异常");
    }
  } catch (e) {
    console.error("加载行政部门失败", e);
    ElMessage.error("加载行政部门失败");
  }
};

// 加载行政人员职称信息
const loadProfessionalData = async () => {
  try {
    const res = await getAdminStaffProfessionalList();
    // console.log(res);
    if (res && res.code == 200) {
      professionalOptions.value = res.data.map((p) => ({
        value: Number(p.professional_id),
        label: p.professional_title,
        staff_type: p.staff_type,
      }));
      // ElMessage.success("加载行政人员职称成功");
    } else {
      ElMessage.error("加载行政人员职称失败");
    }
  } catch (e) {
    console.error("加载行政人员职称失败", e);
    ElMessage.error("加载行政人员职称失败");
  }
};

// 加载行政人员列表
const loadAdministrativeStaff = async () => {
  const params = {
    manager_name: filters.administrative_name,
    work_id: filters.work_id,
    department_id: filters.department_id,
    professional_id: filters.professional_id,
    status: filters.status,
    staff_type: activeStaffType.value === "all" ? null : activeStaffType.value,
    currentPage: pagination.currentPage,
    pageSize: pagination.pageSize,
  };

  loading.value = true;
  try {
    const res = await getAdminStaffPagerDataBySearch(params);

    const preload = res.data;

    // console.log(res);

    if (res && res.code == 200) {
      // console.log("加载的行政人员列表:", preload.data);
      administrativeStaffList.value = preload.data;
      pagination.pageTotal = preload.pageTotal || 0;
      pagination.total = preload.total || 0;
      // ElMessage.success("加载行政人员列表成功");
    } else {
      ElMessage.error(preload?.message || "加载行政人员列表失败");
    }
  } catch (e) {
    console.error("加载行政人员列表失败", e);
    ElMessage.error("加载行政人员列表失败");
  } finally {
    loading.value = false;
  }
};

const handleSizeChangeHandle = (size) => {
  pagination.pageSize = size;
  loadAdministrativeStaff();
};

const handleCurrentChangeHandle = (page) => {
  pagination.currentPage = page;
  loadAdministrativeStaff();
};

const viewAdministrativeStaffDetailsHandle = (staff) => {
  Object.assign(detailInfo, {
    manager_id: staff.manager_id ?? null,
    work_id: staff.work_id ?? "",
    manager_name: staff.manager_name ?? "",
    manager_avatar: staff.manager_avatar ?? "",
    staff_type: staff.staff_type ?? "",
    professional_id: staff.professional_id ?? null,
    sex: staff.sex ?? 1,
    phone: staff.phone ?? "",
    status: staff.status ?? 1,
    department_id: staff.department_id ?? null,
    department_name: staff.department_name ?? "",
    good_at: staff.good_at ?? "",
    description: staff.description ?? "",
    username: staff.username ?? "",
  });

  if (!detailInfo.department_name && detailInfo.department_id) {
    detailInfo.department_name = getDepartmentLabel(detailInfo.department_id);
  }

  detailDrawer.visible = true;
};

const openEditFromDrawerHandle = () => {
  editAdministrativeStaffHandle({ ...detailInfo });
  detailDrawer.visible = false;
};

const editAdministrativeStaffHandle = (staff) => {
  Object.assign(administrativeForm, {
    ...staff,
    userpass: "",
    professional_id: staff.professional_id
      ? Number(staff.professional_id)
      : null,
    manager_name: staff.manager_name ?? "",
    manager_avatar: staff.manager_avatar ?? "",
  });
  // 设置对应的职称选项
  handleStaffTypeChangeHandle();

  administrativeDialog.isEdit = true;
  administrativeDialog.visible = true;
};

const deleteAdministrativeStaffHandle = (staff) => {
  ElMessageBox.confirm(
    `确定要删除${formatStaffType(staff.staff_type)} ${
      staff.manager_name
    } 吗？此操作不可恢复！`,
    "删除确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      // 调用删除接口
      administrativeStaffList.value = administrativeStaffList.value.filter(
        (s) => s.manager_id !== staff.manager_id
      );
      ElMessage.success("删除成功");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const beforeAvatarUploadHandle = (file) => {
  const fileExt = file.name.substring(file.name.lastIndexOf(".")).toLowerCase();
  const isValidType = [".jpg", ".jpeg", ".png"].includes(fileExt);
  const isLt2M = file.size / 1024 / 1024 < 4;

  if (!isValidType) {
    ElMessage.error("只支持JPG、JPEG和PNG格式的图片！");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过2MB！");
    return false;
  }
  return true;
};

const handleAvatarChangeHandle = async (params) => {
  try {
    const formData = new FormData();
    formData.append("file", params.file);
    const res = await uploadAvatar(formData);
    console.log("上传头像响应:", res);
    if (res.code == 200) {
      administrativeForm.manager_avatar = res.data || "";
      ElMessage.success("头像上传成功");
    } else {
      ElMessage.error("头像上传失败");
    }
  } catch (e) {
    console.error("头像上传失败", e);
    ElMessage.error("头像上传失败");
  }
};

const handleStaffTypeChangeHandle = () => {
  // 根据人员类型过滤对应的职称选项
  filterProfessionTitleOptions.value = professionalOptions.value.filter(
    (prof) => prof.staff_type === administrativeForm.staff_type
  );

  // 设置默认职称（选择过滤后的第一个选项）
  if (filterProfessionTitleOptions.value.length > 0) {
    administrativeForm.professional_id =
      filterProfessionTitleOptions.value[0].value;
  } else {
    administrativeForm.professional_id = null;
  }
};

const showAddAdministrativeStaffDialogHandle = () => {
  Object.assign(administrativeForm, {
    administrative_id: null,
    work_id: "",
    manager_name: "",
    manager_avatar: "",
    staff_type: "administrative_manager",
    professional_id: null,
    professional_name: "",
    sex: 1,
    phone: "",
    department_id: "",
    status: 1,
    good_at: "",
    description: "",
    username: "",
    userpass: "",
  });

  // 设置默认职称
  const defaultProf = dialogProfessionalOptions.value[0];
  if (defaultProf) {
    administrativeForm.professional_id = defaultProf.value;
  }

  administrativeDialog.isEdit = false;
  administrativeDialog.visible = true;

  handleStaffTypeChangeHandle();
};

const submitAdministrativeFormHandle = async () => {
  try {
    await administrativeFormRef.value.validate();

    // 动态设置验证规则
    const dynamicRules = { ...administrativeRules.value };

    if (administrativeDialog.isEdit) {
      delete dynamicRules.username;
      delete dynamicRules.userpass;
    }

    // 重新验证
    administrativeFormRef.value.clearValidate();
    await administrativeFormRef.value.validate();

    const payload = {
      manager_id: administrativeForm.manager_id,
      work_id: administrativeForm.work_id,
      manager_name: administrativeForm.manager_name,
      manager_avatar: administrativeForm.manager_avatar || defaultAvatar,
      staff_type: administrativeForm.staff_type,
      professional_id: Number(administrativeForm.professional_id),
      sex: Number(administrativeForm.sex),
      phone: administrativeForm.phone,
      status: Number(administrativeForm.status),
      department_id: Number(administrativeForm.department_id),
      good_at: administrativeForm.good_at,
      description: administrativeForm.description,
      username: administrativeForm.username,
      ...(administrativeDialog.isEdit
        ? {}
        : { userpass: administrativeForm.userpass }),
    };

    let resp;
    if (administrativeDialog.isEdit) {
      resp = await editManager(payload);
    } else {
      resp = await addManager(payload);
    }

    let data = resp;
    if (resp && resp.data) {
      data = resp.data;
    }

    if (data && data.code == 200) {
      ElMessage.success(administrativeDialog.isEdit ? "编辑成功" : "新增成功");
      administrativeDialog.visible = false;
      loadAdministrativeStaff();
    } else {
      ElMessage.error(
        data?.message || (administrativeDialog.isEdit ? "编辑失败" : "新增失败")
      );
    }
  } catch (e) {
    console.error("提交表单失败", e);
    if (e && e.message) {
      ElMessage.error(e.message);
    }
  }
};

const exportDataHandle = () => {
  ElMessage.info("导出数据功能开发中...");
};

const refreshDataHandle = () => {
  loadAdministrativeStaff();
  ElMessage.success("刷新成功");
};

// 格式化方法
const formatStaffType = (type) => {
  const typeMap = {
    administrative_manager: "行政管理人员",
    administrative_technician: "行政技术人员",
    system_administrator: "系统管理员",
  };
  return typeMap[type] || type;
};

const getStaffTypeTag = (type) => {
  const tagMap = {
    administrative_manager: "primary",
    administrative_technician: "success",
    system_administrator: "danger",
  };
  return tagMap[type] || "info";
};

const formatSex = (sex) => {
  return sex === 0 ? "男" : sex === 1 ? "女" : "未知";
};

const formatStatus = (status) => {
  const statusMap = {
    1: "在职",
    2: "休假",
    3: "离职",
  };
  return statusMap[status] || "未知";
};

const statusTagType = (status) => {
  const typeMap = {
    1: "success",
    2: "warning",
    3: "info",
  };
  return typeMap[status] || "info";
};

const formatTitle = (professionalId) => {
  const prof = professionalOptions.value.find(
    (p) => p.value === professionalId
  );
  return prof ? prof.label : "未知";
};

const formatManagementLevel = (level) => {
  const levelMap = {
    junior: "初级管理",
    middle: "中级管理",
    senior: "高级管理",
    executive: "决策层",
  };
  return levelMap[level] || level;
};

const formatTechnicalField = (field) => {
  const fieldMap = {
    it: "信息技术",
    equipment: "设备维护",
    network: "网络管理",
    operation: "系统运维",
    support: "技术支持",
  };
  return fieldMap[field] || field;
};

const formatTechnicalLevel = (level) => {
  const levelMap = {
    junior: "初级",
    middle: "中级",
    senior: "高级",
    expert: "专家",
  };
  return levelMap[level] || level;
};

const getDepartmentLabel = (departmentId) => {
  const dept = administrativeDepartmentOptions.value.find(
    (d) => d.value === departmentId
  );
  return dept ? dept.label : "未知部门";
};

const getTableTitle = () => {
  const typeMap = {
    all: "全部行政人员",
    administrative_manager: "行政管理人员",
    administrative_technician: "行政技术人员",
  };
  return typeMap[activeStaffType.value] || "行政人员管理";
};

// 初始化
onMounted(async () => {
  await loadProfessionalData();
  await loadAdministrativeDepartments();

  loadAdministrativeStaff();
});
</script>

<style lang="scss" scoped>
.content-area {
  flex: 1;
  padding: 24px;
  background-color: #f5f7fa;
  height: 0; // 添加这行
  min-height: 100%; // 添加这行
  overflow-y: auto; // 确保有这行
}

.type-tabs-card {
  background: white;
  border-radius: 12px;
  padding: 16px 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.type-tabs {
  display: flex;
  justify-content: center;
}

.filter-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  min-width: 200px;
  flex: 1;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 16px;
}

.administrative-table {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.table-tools {
  display: flex;
  gap: 12px;
}

.staff-info {
  display: flex;
  align-items: center;
}

.staff-avatar {
  margin-right: 12px;
}

.staff-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.staff-details {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 6px;
}

.level-info {
  color: #409eff;
  font-weight: 500;
}

.action-buttons-cell {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: flex-start;

  .el-avatar {
    border: 1px solid #ebeef5;
    background: #f5f7fa;
  }
}

.drawer-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 18px 0;
  border-bottom: 1px solid #f0f0f0;

  .drawer-title {
    .name {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }

    .meta {
      font-size: 13px;
      color: #909399;
      margin-top: 6px;
    }
  }
}

.drawer-content {
  padding: 16px 0;
  max-height: calc(100vh - 200px);
  overflow: auto;
}

// 覆盖Element Plus组件样式
:deep(.el-radio-group) {
  width: 100%;
  display: flex;
  justify-content: center;
}

:deep(.el-radio-button) {
  flex: 1;
  text-align: center;
}

:deep(.el-radio-button__inner) {
  width: 100%;
}

:deep(.el-descriptions) {
  .el-descriptions__label {
    font-weight: 500;
    color: #606266;
  }

  .el-descriptions__content {
    color: #303133;
  }
}

:deep(.el-table) {
  .el-table__header {
    th {
      background-color: #f8f9fa;
      font-weight: 600;
      color: #303133;
    }
  }

  .el-table__body {
    tr:hover > td {
      background-color: #f5f7fa !important;
    }
  }
}

:deep(.el-dialog) {
  border-radius: 12px;

  .el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #ebeef5;

    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }

  .el-dialog__body {
    padding: 20px;
  }

  .el-dialog__footer {
    padding: 10px 20px 20px;
    border-top: 1px solid #ebeef5;
  }
}

:deep(.el-drawer) {
  .el-drawer__header {
    margin-bottom: 0;
    padding: 20px;
    border-bottom: 1px solid #ebeef5;

    .el-drawer__title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }

  .el-drawer__body {
    padding: 0;
  }

  .el-drawer__footer {
    padding: 20px;
    border-top: 1px solid #ebeef5;
  }
}



:deep(.el-form) {
  .el-form-item {
    margin-bottom: 18px;

    .el-form-item__label {
      font-weight: 500;
      color: #606266;
    }
  }
}

:deep(.el-tag) {
  border: none;
  font-weight: 500;

  &.el-tag--primary {
    background-color: #ecf5ff;
    color: #409eff;
  }

  &.el-tag--success {
    background-color: #f0f9eb;
    color: #67c23a;
  }

  &.el-tag--warning {
    background-color: #fdf6ec;
    color: #e6a23c;
  }

  &.el-tag--danger {
    background-color: #fef0f0;
    color: #f56c6c;
  }

  &.el-tag--info {
    background-color: #f4f4f5;
    color: #909399;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .content-area {
    padding: 16px;
  }

  .filter-row {
    flex-direction: column;
    gap: 12px;
  }

  .filter-item {
    min-width: 100%;
  }

  .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .table-tools {
    width: 100%;
    justify-content: flex-end;
  }

  .action-buttons {
    flex-wrap: wrap;
  }

  .action-buttons-cell {
    flex-direction: column;
    gap: 4px;
  }

  :deep(.el-radio-group) {
    flex-direction: column;
    gap: 8px;
  }

  :deep(.el-radio-button) {
    flex: none;
  }
}

// 抽屉自定义头部
.drawer-custom-header {
  h3 {
    margin: 0;
    color: #303133;
    font-size: 18px;
    font-weight: 600;
  }
}

.drawer-content-wrapper {
  padding: 0 20px;
  height: 100%;
  overflow-y: auto;
}

// 个人信息卡片
.staff-profile-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  color: white;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -50%;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
  }
}

.profile-header {
  display: flex;
  align-items: center;
  gap: 16px;
  position: relative;
  z-index: 1;
}

.profile-avatar {
  border: 3px solid rgba(255, 255, 255, 0.2);
}

.profile-info {
  flex: 1;
  
  .staff-name {
    margin: 0 0 8px 0;
    font-size: 24px;
    font-weight: 600;
    color: white;
  }
  
  .staff-meta {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 8px;
    
    .work-id {
      font-size: 14px;
      opacity: 0.9;
    }
  }
}

// 详细信息区域
.detail-sections {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f5f5f5;
  
  .el-icon {
    color: #409eff;
    font-size: 16px;
  }
  
  span {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.section-content {
  .info-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
  }
  
  .info-item {
    display: flex;
    flex-direction: column;
    gap: 4px;
    
    label {
      font-size: 13px;
      color: #909399;
      font-weight: 500;
    }
    
    span {
      font-size: 14px;
      color: #303133;
      font-weight: 500;
      
      &.username {
        color: #409eff;
        font-family: 'Courier New', monospace;
      }
    }
  }
  
  .info-item-full {
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin-bottom: 16px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    label {
      font-size: 13px;
      color: #909399;
      font-weight: 500;
    }
    
    .info-content {
      font-size: 14px;
      color: #303133;
      line-height: 1.5;
      
      &.description-text {
        background: #f8f9fa;
        padding: 12px;
        border-radius: 6px;
        border-left: 3px solid #409eff;
      }
    }
  }
}

// 抽屉底部
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
}

// 暗色主题适配
@media (prefers-color-scheme: dark) {
  .content-area {
    background-color: #1a1a1a;
  }

  .type-tabs-card,
  .filter-card,
  .administrative-table {
    background: #2d2d2d;
    color: #e0e0e0;
  }

  .table-title {
    color: #e0e0e0;
  }

  .staff-name {
    color: #e0e0e0;
  }

  :deep(.el-table) {
    background: #2d2d2d;
    color: #e0e0e0;

    .el-table__header {
      th {
        background-color: #3d3d3d;
        color: #e0e0e0;
      }
    }

    .el-table__body {
      tr:hover > td {
        background-color: #3d3d3d !important;
      }
    }
  }
}

// 动画效果
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.slide-enter-active,
.slide-leave-active {
  transition: transform 0.3s ease;
}

.slide-enter-from,
.slide-leave-to {
  transform: translateX(100%);
}
</style>